package com.fengpb.friday.conductor.common.remote;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class RemoteClient {

    private static final Logger log = LoggerFactory.getLogger(RemoteClient.class);

    private static final String PROTOCOL_PREFIX = "http://";

    private final RestTemplate restTemplate;

    public RemoteClient(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * get请求
     * @param serviceName 服务名
     * @param path 请求路径
     * @return 返回值
     */
    public String get(String serviceName, String path) {
        return call(serviceName, path, HttpMethod.GET, String.class, null, null);
    }

    public String get(String serviceName, String path, String json) {
        return call(serviceName, path, HttpMethod.GET, String.class, json, null);
    }

    public String post(String serviceName, String path) {
        return call(serviceName, path, HttpMethod.POST, String.class, null, null);
    }

    public String post(String serviceName, String path, String json) {
        return call(serviceName, path, HttpMethod.POST, String.class, json, null);
    }

    public <T> T get(String serviceName, String path, Class<T> responseType, String json) {
        return call(serviceName, path, HttpMethod.GET, responseType, json, null);
    }

    public <T> T post(String serviceName, String path, Class<T> responseType, String json) {
        return call(serviceName, path, HttpMethod.POST, responseType, json, null);
    }

    public <T> T call(String serviceName, String path, HttpMethod method, Class<T> responseType, String json, HttpHeaders headers) {
        path = path.startsWith("/") ? path : "/" + path;
        ResponseEntity<T> response;
        HttpEntity<Object> requestEntity = new HttpEntity<>(json, headers);
        String url = PROTOCOL_PREFIX + serviceName + path;
        try {
            response = restTemplate.exchange(url, method, requestEntity, responseType);
        } catch (Exception e) {
            String service = "service";// TODO
            log.error("RemoteClient调用远端服务发生异常：[ service = ]" + service + "，errorMessage = " + e.getMessage(), e);
            throw e;
        }
        return response.getBody();
    }
}
